﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.uplus.rabbitmqhelper
{
    public class RabbitMQProductor:RabbitMQBase
    {
        #region 发送消息（需要先创建交换机，或者保证交换机已存在，否则会报错）
        /// <summary>
        /// 发送消息（需要先创建交换机，或者保证交换机已存在，否则会报错）
        /// </summary>
        /// <param name="exchange">交换机名称</param>
        /// <param name="routingKey">路由键</param>
        /// <param name="msgBody">需要发送的内容</param>
        /// Creator:LM  Time: 2018年3月21日16:05:14
        public void SendMessage(string exchange, string routingKey, byte[] msgBody)
        {
            try
            {
                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;
                channel.BasicPublish(exchange, routingKey, properties, msgBody);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 清空队列
        /// <summary>
        /// 清空队列
        /// </summary>
        /// <param name="queue"></param>
        public void QueueDelete(string queue)
        {
            try
            {
               channel.QueueDelete(queue);             
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取队列中的消息个数
        /// <summary>
        /// 获取队列中的消息个数
        /// </summary>
        /// <param name="queue"></param>
        public int QueueCount(string queue)
        {
            try
            {
                QueueDeclareOk declareOk = channel.QueueDeclarePassive(queue);
                //获取队列中的消息个数
                return (int)declareOk.MessageCount;              
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
